package com.sloth.bear.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sloth.bear.common.ResultCode;
import com.sloth.bear.dto.entity.NameSpace;
import com.sloth.bear.dto.request.NameSpaceRequest;
import com.sloth.bear.dto.vo.NameSpaceVo;
import com.sloth.bear.exception.BusinessException;
import com.sloth.bear.mapper.NameSpaceMapper;
import com.sloth.bear.service.NameSpaceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 命名空间服务实现类
 */
@RequiredArgsConstructor
@Service
public class NameSpaceServiceImpl implements NameSpaceService {

    private final NameSpaceMapper nameSpaceMapper;

    @Override
    public List<NameSpaceVo> getAllSpaces() {
        LambdaQueryWrapper<NameSpace> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(NameSpace::getSortNo)
               .orderByDesc(NameSpace::getCreatedTime);
        
        List<NameSpace> spaces = nameSpaceMapper.selectList(wrapper);
        return spaces.stream()
                    .map(this::convertToVo)
                    .collect(Collectors.toList());
    }

    @Override
    public NameSpaceVo getSpaceById(Long id) {
        NameSpace space = nameSpaceMapper.selectById(id);
        if (space == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }
        return convertToVo(space);
    }

    @Override
    public NameSpaceVo createSpace(NameSpaceRequest request) {
        NameSpace space = new NameSpace();
        space.setName(request.getName());
        space.setDescription(request.getDescription());
        space.setColor(request.getColor());
        space.setSortNo(request.getSortNo() != null ? request.getSortNo() : 0);

        int result = nameSpaceMapper.insert(space);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "创建命名空间失败");
        }
        return convertToVo(space);
    }

    @Override
    public NameSpaceVo updateSpace(Long id, NameSpaceRequest request) {
        NameSpace existSpace = nameSpaceMapper.selectById(id);
        if (existSpace == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }

        existSpace.setName(request.getName());
        existSpace.setDescription(request.getDescription());
        existSpace.setColor(request.getColor());
        existSpace.setSortNo(request.getSortNo() != null ? request.getSortNo() : 0);

        int result = nameSpaceMapper.updateById(existSpace);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "更新命名空间失败");
        }
        return convertToVo(existSpace);
    }

    @Override
    public boolean deleteSpace(Long id) {
        if (id == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间ID不能为空");
        }

        NameSpace existSpace = nameSpaceMapper.selectById(id);
        if (existSpace == null) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "命名空间不存在");
        }

        // 检查是否还有文档关联此空间
        Integer documentCount = nameSpaceMapper.countDocumentsByNamespaceId(id);
        if (documentCount > 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "该空间下还有文档，无法删除");
        }

        int result = nameSpaceMapper.deleteById(id);
        if (result <= 0) {
            throw new BusinessException(ResultCode.BAD_REQUEST.getCode(), "删除命名空间失败");
        }
        return true;
    }

    private NameSpaceVo convertToVo(NameSpace space) {
        NameSpaceVo vo = new NameSpaceVo();
        BeanUtils.copyProperties(space, vo);
        // 统计文档数量
        vo.setDocumentCount(nameSpaceMapper.countDocumentsByNamespaceId(space.getId()));
        return vo;
    }
}